<template>
  <layout class="dept-agent-config">
    <template  slot="card">
      <div class="da-tree__wapper">
        <div class="da-tree__heardwapper" >
            <div class="da-tree__heard">
            <h3 class="title">{{$t('config.agent.directory')}}</h3>
            <!--<a @click.stop="searchAgentData('noDept')" class="unassgin">{{$t('config.agent.notAssignedDept')}}</a>-->
          </div>
        </div>
        <div class="da-tree__content">
          <dept-tree
            @searchAgent = "searchAgent"
            @nodeClick="searchDeptAgentData"
            class="tree"
          ></dept-tree>
        </div>
      </div>
    </template>
    <template slot="detail">
      <div class="da-info__wapper">
        <div class="da-info__title">
          <!--<h3>{{$t('config.agent.employeeInformation')}}</h3>-->
          <div class="list__tip">
            <span>{{$t('config.agent.packageTypeTip')}}</span>
            <span v-for="(item, index) in versions" :key="index">
                  {{`${item.value}${$t('config.agent.packageTypeTip1')}${item.label}`}} <template v-if="versions.length-1 === index">。  </template><template v-else>、</template>
              <!-- {{$t('config.agent.packageTypeConfig', {num1: 2, num2: 3, num3: 0, num4: 0, num5: 5})}} -->
                </span>
            <span>{{$t('config.agent.packageTypeTip2')}}</span>
            <span v-for="(item, index) in versions" :key="'key' + index">
                  {{`${item.value1}${$t('config.agent.packageTypeTip1')}${item.label1}`}} <template v-if="versions.length-1 === index">。</template><template v-else>、</template>
                </span>
            <el-tooltip
              transition="fade-leave"
              effect="dark"
              :content="$t('config.agent.packageLegent')"
              placement="bottom">
              <i class="icon iconfont icon-tixingweizhi"></i>
            </el-tooltip>
          </div>
        </div>
        <div class="da-info__content">
          <affix
          :label="$t('config.agent.searchAgent')"
          class="da-info__search">
            <search-agent
              :isAssDept="isAssDept"
              @search="searchAgentData"
              ref="searchAgent"
            >
            </search-agent>
          </affix>
          <affix
          :label="$t('config.agent.searchAgentList')"
          class="da-info__list">
            <div class="list__title" v-if="versions.length !== 0">
              <div class="list--btn" v-if="false"><!-- 一期不做账号设置中的购买，先隐藏跳转按钮 -->
                <el-button type="primary" class="buy__btn primary_btn" @click.stop="onSubmit">{{$t('config.agent.buyPackage')}}</el-button>
              </div>
            </div>
            <search-agent-list
              :tableData = "tableData"
              :trunPage ="trunPage"
              @trunPages="trunPages"
              @refrech="refrech"
              :total = "total"
            >
            </search-agent-list>
          </affix>
          </div>
        </div>
    </template>
  </layout>
</template>
<script>
  import Affix from '@/components/ui-modules/affix/Affix'
  import Layout from '@/components/ui-modules/right-layout/RightLayout'
  import DeptTree from './tree/DeptTree'
  import SearchAgent from './info/SearchAgent'
  import SearchAgentList from './info/SearchAgentList'
  import { deepClone, removeEmptyProperty } from '@/utils/m7Utils'

  export default {
    name: 'AgentConfig',
    data () {
      return {
        isAssDept: true,
        licenceType: [],
        data: {
          page: 1,
          limit: 10
        },
        trunPage: 1,
        deptId: '',
        treeData: [],
        tableData: [],
        depts: [],
        roles: [],
        count: 0,
        versions: [],
        total: 0,
        callQueueList:[],
        webchatQueueList:[],
      }
    },
    components: {
      Layout,
      Affix,
      DeptTree,
      SearchAgent,
      SearchAgentList
    },
    methods: {
      // 接受树组件传出来的方法搜索table数据并进行渲染
      searchAgent () {
        getTableData(this, this.data)
        .then((depts) => {
          this.total = depts.count
          this.tableData = this.dealQueryUser(depts.list)
        })
      },
      /**
       * [searchAgentData description]
       * @param  {[type]} form
       *  [description]
       * @return {[type]}     [description]
       * 根据部门Id查询相关座席
       * 当 deptId 是 'noDept' 时 查询的是未分配的部门
       */
      searchAgentData (form) {
        this.trunPage = 1
        let req = deepClone(this.data)
        if (typeof form === 'string') {
          let data = {
            page: 1,
            limit: 10
          }
          req = deepClone(data)
          req.deptId = form
          this.deptId = form
          req = removeEmptyProperty(req)
        } else {
          req = deepClone(form)
          req = removeEmptyProperty(req)
          req.deptId = this.deptId
        }
        getTableData(this, req)
        .then((resp) => {
          this.total = resp.count
          this.tableData = this.dealQueryUser(resp.list)
        })
      },
      // 由于判断繁琐抽出来的通过pID判断是不是全公司是不传方法
      searchDeptAgentData (form) {
        this.trunPage = 1
        this.$refs.searchAgent.resetFrom() // 点击部门树形的时候，重置表单
        if (form.pId === '') {
          this.isAssDept = true
        } else {
          this.isAssDept = false
        }
        let req = {
          page: 1,
          limit: 10
        }
        if (form.pId) {
          req.deptId = form._id
          this.deptId = form._id
        } else {
          this.deptId = ''
        }
        req = removeEmptyProperty(req)
        getTableData(this, req)
        .then((resp) => {
          this.total = resp.count
          this.tableData = this.dealQueryUser(resp.list)
        })
      },
      trunPages (page) {
        this.data = deepClone(this.$store.state.config.agentConfig.queryAgent)
        this.data.page = page
        this.data.limit = 10
        this.trunPage = page

        getTableData(this, this.data)
        .then((depts) => {
          this.total = depts.count
          this.tableData = this.dealQueryUser(depts.list)
        })
      },
      refrech () {
        this.data = this.$store.state.config.agentConfig.queryAgent
//        if (this.trunPage !== 1) {
//          this.trunPage = 1
//          return
//        }
        getTableData(this, this.data)
        .then((depts) => {
//          this.trunPage = 1
          if (depts && depts.success) {
            if (depts.list.length === 0) {
              // 算出最后一页的页数
              let page = Math.ceil(depts.count / 10)
              this.trunPages(page)
            } else {
              this.total = depts.count
              this.tableData = this.dealQueryUser(depts.list)
            }
          }
        })
      },

      getDeptName (id) {
        for (let i in this.depts) {
          if (this.depts[i]._id === id) {
            return this.depts[i].name
          }
        }
        return ''
      },
      /**
       *  需修改 状态
       * [dealQueryUser description]
       * @param  {[type]} data [description]
       * @return {[type]}      [description]
       */
      dealQueryUser (data) {
        data.forEach(item => {
          //技能组名称
          if(item.callQueues && item.callQueues.length>0){
            item.callQueueNamesArr = []
            if(this.callQueueList && this.callQueueList.length > 0) {
              this.callQueueList.forEach(val=>{
                item.callQueues.forEach(val1=>{
                  if(val1 === val._id){
                    item.callQueueNamesArr.push(val.DisplayName)
                  }
                })
              })
            }
          }
          if(item.mailQueues && item.mailQueues.length>0){
            item.mailQueueNamesArr = []
            if(this.webchatQueueList.data && this.webchatQueueList.data.length > 0) {
              this.webchatQueueList.data.forEach(val=>{
                item.mailQueues.forEach(val1=>{
                  if(val1 === val._id){
                    item.mailQueueNamesArr.push(val.DisplayName)
                  }
                })
              })
            }
          }
          item.displayName = `${item.displayName}(${item.exten})`
          item.deptName = this.getDeptName(item.deptId) || this.$t('config.agent.notAssignedDept')
          item.parentId = item.parentId
          item.roleName = this.dealRole(item.role)
          item.mobile = item.mobile
          item.status = item.status
          item.uversion1 = this.dealLicenceType(item.uversion)
          item._id = item._id
          if(item.callQueueNamesArr && item.callQueueNamesArr.length>0){
            item.callQueueNames = item.callQueueNamesArr.join(';')
          }
          if(item.mailQueueNamesArr && item.mailQueueNamesArr.length>0){
            item.mailQueueNames = item.mailQueueNamesArr.join(';')
          }
        })
        return data
      },
      // 处理座席使用版本
      dealLicenceType (data) {
        let _value = ''
        for (let i = 0; i < this.licenceType.length; i++) {
          if (this.licenceType[i].code_value === data) {
            _value = this.licenceType[i].code_name
            break
          }
        }
        return _value
      },
      dealRole (data) {
        let arrRole = []
        for (let i in data) {
          for (let j in this.roles) {
            data[i] === this.roles[j]._id &&
            arrRole.push(this.roles[j].display_name)
          }
        }
        return arrRole.toString()
      },
      dealVersionNum () {
        let response = []
        this.$store.dispatch('queryVersionNum', {})
        .then((res) => {
          if (res && res.success) {
            response = res.uversions
            let Packages = deepClone(this.$getCache('licenceType'))
            for (let i in response) {
              for (let j = 0; j < Packages.length; j++) {
                if (response[i]._id === Packages[j].code_value) {
                  this.versions.push({
                    label: Packages[j].code_name,
                    value: response[i].count,
                    label1: `${Packages[j].code_name}licence`,
                    value1: response[i].brrowLicenceCount
                  })
                }
              }
            }
          }
        })
      }
    },
    beforeMount () { 
      let data = {
        Account: this.$store.state.session.account.account
      }
      this.$store.dispatch('queryQueueForSkill', data).then(res => {
        if (res.success) {
          this.callQueueList = res.list || []
        }
      })
      Promise.all([
        this.$store.dispatch('getCache', { type: 'depts' }),
        this.$store.dispatch('getCache', {type: 'roles'}),
        this.$store.dispatch('getCache', { type: 'licenceType' }),
        this.$store.dispatch('getDicCache', { type: 'mailQueues' }),
      ])
      .then(([depts, roles, licenceType, mailQueues]) => {
        this.roles = roles
        this.depts = depts
        this.licenceType = licenceType
        this.webchatQueueList = mailQueues
      })
      .then(() => {
        getTableData(this, this.data).then((res) => {
          if (res && res.success) {
            this.total = res.count
            this.tableData = this.dealQueryUser(res.list)
          }
        })
      }).then(() => {
        this.dealVersionNum()
      })
    }
  }
  // 获取座席信息
  function getTableData (vm, data) {
    return vm.$store.dispatch('queryUser', data)
  }
</script>
<style lang="stylus" scoped>
  @import "../../../../assets/common.styl"
  $width=340px
  $t-height=40px
  .icon-tixingweizhi
    box-sizx(15px)
    border 1px solid $c-main
    border-radius 8px
    color $c-main
    font-size 12px

  .da-tree__wapper
    height 100vh
    background #fff
    .da-tree__heardwapper
      border-bottom 1px solid $c-border1
      .da-tree__heard
        height $t-height
        margin 0 12px
        display flex
        justify-content space-between
        align-items center
  .da-info__wapper
    overflow-x auto
    .da-info__title
      padding 10px
      color $c-prompt
      border-bottom 1px solid $c-border1
      h3
        font-size 14px
        line-height $t-height
        margin-left 22px
    .da-info__content
      margin-top 20px
      padding-bottom 25px
      height calc(100vh - 160px)
      margin-left 15px
      overflow-y auto
      .da-info__search
        padding-bottom 4px
  .da-info__list
    .list__title
      display flex
      justify-content space-between
      align-items center
      margin-bottom 6px
</style>
